package com.bestcem.xm.common.core.uitls;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 * 事务工具类
 *
 * @author dc.wang <dc.wang@idiaoyan.com>
 * @version V1.0
 * @date 2022/8/10 17:51
 */
@Slf4j
public class TransactionHelper {
    private TransactionHelper() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 事务完成后执行任务
     *
     * @param runnable 任务
     */
    public static void runAfterCommit(Runnable runnable) {
        // 是否开启事务判断
        if (TransactionSynchronizationManager.isSynchronizationActive()) {
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
                @Override
                public void afterCommit() {
                    runnable.run();
                }
            });
        } else {
            runnable.run();
        }
    }

}
